import {reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogOut} from '@/api/index'
const actions={
   async getCode(context,phone){
        let result= await reqGetCode(phone)
        if(result.code==200){
            context.commit('GETCODE',result.data)
            return 'ok'
        }else{
           return Promise.reject(new Error('faile'))
        }
    },
   async userRegister(context,data){
       let result =await reqUserRegister(data)
       console.log(result)
        if(result.code==200){
         return 'ok'
        }else{
          return Promise.reject(new Error('faile'))
        }
    },
   async userLogin(context,data){
        let result=await reqUserLogin(data)
        //服务器下发token,用户唯一标识符（类似uuid）
        //将来经常通过token找服务器要用户信息进行展示
        if(result.code==200){
            context.commit('USERLOGIN',result.data.token);
            localStorage.setItem('TOKEN',result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    async getUserInfo(context){
        let result=await reqUserInfo();
        if(result.code==200){
            context.commit('GETUSERINFO',result.data);
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
   async userLogOut(context){
        let result =await reqLogOut();
        if(result.code==200){
            context.commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'));
        }

    }
}
const mutations={
    GETCODE(state,code){
        state.code=code
    },
    USERLOGIN(state,token){
      state.token=token
    },
    GETUSERINFO(state,userInfo){
       state.userInfo=userInfo
    },
    CLEAR(state){
      state.token='';
      state.userInfo={};
      localStorage.removeItem('TOKEN')
    }
}
const state={
    code:'',
    token:localStorage.getItem('TOKEN'),
    userInfo:{}
}
const getters={}
export default {
    actions,mutations,state,getters
}